package com.utils;



import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 林沐
 * 数据库工具类
 */
public class DBUtil {
    /**
     * 账号
     */
    static String dbname="root";
    /**
     * 密码
     */
    static String dbpass="root";
    /**
     * 地址
     */
    static String url="jdbc:mysql://localhost:3306/cctv";
    /**
     * 驱动
     */
    static String driver="com.mysql.jdbc.Driver";
    static Statement sta=null;
    static ResultSet rs= null;

    /**
     * 连接方法
     * @return
     */
    public static Connection openconn() {
        Connection conn=null;
        try {
            Class.forName(driver);
            try {
                conn= DriverManager.getConnection(url,dbname,dbpass);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    
    //通用查询
    public static List SelectTabl(String sql,Class clas) throws Exception {
    	List list=new ArrayList();
    	Connection conn=DBUtil.openconn();
		Statement sta=conn.createStatement();
		ResultSet res=sta.executeQuery(sql);
		ResultSetMetaData metdate= res.getMetaData();
		int len=metdate.getColumnCount();//得到列列数
		while(res.next()) {
			Object oobje=clas.newInstance();
			for(int i=1;i<=len;i++) {
				String colname=metdate.getColumnName(i);//得到列名		
//				System.out.println(colname);
				Object obj= res.getObject(colname);
//				System.out.print(obj);
				Field fie=clas.getDeclaredField(colname);
				fie.set(oobje, obj);
			}
			list.add(oobje);
		}
		return list;
    }
}
